<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/2
 */

namespace app\financial\controller;


use app\classes\model\ClassModel;
use app\course\model\CourseModel;
use app\financial\model\OrderModel;
use app\system\model\SchoolModel;
use app\financial\model\BillModel;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Exception;

class FinancialController extends AdminBaseController
{
    /**
     * 财务收入
     * @return mixed
     */
    public function index()
    {
        $param = $this->request->param();
        $limit = config('limit_per_page');
        $classes = [];
        $class_mdl = new ClassModel();

        $where = [
            'o.shop_id' => ['=', $this->admin_shop_id],
        ];

        if (!empty($param['school_id']) && is_numeric($param['school_id'])) {
            //学校
            $where['cl.school_id'] = intval($param['school_id']);

            //获取该学校的班级
            $class_where = [
                'shop_id' => ['eq', $this->admin_shop_id],
                'school_id' => ['eq', $param['school_id']],
            ];
            $class = $class_mdl->getClassByField($class_where);
            if (count($class) > 0) {
                $classes = $class;
            }

            if (!empty($param['class_id']) && is_numeric($param['class_id'])) {
                //班级
                $where['o.class_id'] = intval($param['class_id']);
            }
        }

        if (!empty($param['course_id']) && is_numeric($param['course_id'])) {
            //课程
            $where['cl.course_id'] = intval($param['course_id']);
        }

        if (isset($param['payment']) && is_numeric($param['payment']) && $param['payment'] != -1) {
            //缴费方式
            $where['o.payment'] = intval($param['payment']);
        }

        if (isset($param['bill_status']) && is_numeric($param['bill_status']) && $param['bill_status'] != -1) {
            //发票状态
            $where['o.bill_status'] = intval($param['bill_status']);
        }

        if (isset($param['order_status']) && is_numeric($param['order_status']) && $param['order_status'] != -1) {
            //支付状态
            $where['o.order_status'] = intval($param['order_status']);
        }

        if (!empty($param['start']) && !empty($param['end'])) {
            //缴费时间
            $start = strtotime($param['start']);
            $end = strtotime('+23 hours 59 minutes 59 seconds', strtotime($param['end']));
            $where['o.pay_time'] = [['>= time', $start], ['<= time', $end]];
        } else {
            if (!empty($param['start'])) {
                $where['o.pay_time'] = ['>= time', strtotime($param['start'])];
            }
            if (!empty($param['end'])) {
                $end = strtotime('+23 hours 59 minutes 59 seconds', strtotime($param['end']));
                $where['o.pay_time'] = ['<= time', $end];
            }
        }

        //分页附加参数
        $page_query = [
            'school_id' => isset($param['school_id']) ? $param['school_id'] : '',
            'class_id' => isset($param['class_id']) ? $param['class_id'] : '',
            'course_id' => isset($param['course_id']) ? $param['course_id'] : '',
            'payment' => isset($param['payment']) ? $param['payment'] : '-1',
            'bill_status' => isset($param['bill_status']) ? $param['bill_status'] : '-1',
            'order_status' => isset($param['order_status']) ? $param['order_status'] : '-1',
            'start' => isset($param['start']) ? $param['start'] : '',
            'end' => isset($param['end']) ? $param['end'] : '',
        ];

        //排序
        $sort = ['o.order_status' => 'asc'];

        //获取订单
        $order_mdl = new OrderModel();
        $data = $order_mdl->getOrder($where, $sort, $limit, $page_query);

        //获取学校
        $school_mdl = new SchoolModel();
        $schools = $school_mdl->getAllSchool($this->admin_shop_id);
        //获取课程
        $course_mdl = new CourseModel();
        $courses = $course_mdl->getAllCourse($this->admin_shop_id);

        $this->assign('param', $param);
        $this->assign('classes', $classes);
        $this->assign('schools', $schools);
        $this->assign('courses', $courses);
        $this->assign('order', $data);
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    /**
     * 获取班级
     * @return \think\response\Json
     */
    public function ajax_class()
    {
        if ($this->request->isPost()) {
            $param = $this->request->post();

            if (empty($param['school_id'])) {
                $json_data = [
                    'code' => 0,
                    'msg' => '学校不能为空',
                    'data' => []
                ];
                return json($json_data);
            }

            //获取班级
            $where = [
                'shop_id' => ['eq', $this->admin_shop_id],
                'school_id' => ['eq', $param['school_id']],
            ];
            $class_mdl = new ClassModel();
            $data = $class_mdl->getClassByField($where);

            if (count($data) < 0) {
                $json_data = [
                    'code' => 0,
                    'msg' => '没有更多数据',
                    'school_id' => $param['school_id'],
                    'data' => $data
                ];
                return json($json_data);
            }

            $json_data = [
                'code' => 1,
                'msg' => 'success',
                'school_id' => $param['school_id'],
                'data' => $data
            ];
            return json($json_data);
        }
    }

    /**
     * 同意开发票
     */
    public function handle_bill()
    {
        $cur_time = time();
        $table = 'order';
        $order_mdl = new OrderModel();

        $param = $this->request->param();
        if (isset($param['id']) && is_numeric($param['id'])) {
            $id = $param['id'];
            $pk = $id;
            //同意开发票
            $data = [
                'id' => $id,
                'bill_status' => 2,//发票状态(0:不需要，1:待开，2已开)
                'update_time' => $cur_time
            ];
            $res = $order_mdl->editOrder($data);
            if ($res) {
                $data = $order_mdl->alias('o')
                    ->join('student st', 'o.student_id=st.id')
                    ->field('o.*,st.name as student_name')
                    ->where('o.id', '=', $id)
                    ->find();
                //记录日志
                $content = lang('DRAW_BILL', ['name' => $data['student_name']]);
                do_log($content, $pk, $table, $cur_time);

                $this->success("操作成功！");
            } else {
                $this->error('操作失败！');
            }

        } else {
            $this->error('参数有误，操作失败！');
        }
    }

    //查看发票
    public function view_bill()
    {
        $param = $this->request->param();
        if (isset($param['order_id']) && is_numeric($param['order_id'])) {
            $orderId = $param['order_id'];
            $orderModel=new OrderModel();

            $data=$orderModel->alias('or')
                ->field('bill.*,or.id as orderId')
                ->join('bill','bill.id=or.bill_id')
                ->where(['or.id'=>$orderId])
                ->select();
            return $data;
        }else{
            return '参数错误';
        }

    }

    /**
     *导出
     */
    public function exportExcel()
    {
        import('phpexcel.PHPExcel', EXTEND_PATH);
        import('phpexcel.PHPExcel.IOFactory', EXTEND_PATH);
        import('phpexcel.PHPExcel.Reader.Excel5', EXTEND_PATH);

        $param = $this->request->param();
        $where = [
            'o.shop_id' => ['=', $this->admin_shop_id],
            'o.delete_time' => ['=', 0],
        ];

        if (!empty($param['school']) && is_numeric($param['school'])) {
            //学校
            $where['cl.school_id'] = intval($param['school']);

            if (!empty($param['class']) && is_numeric($param['class'])) {
                //班级
                $where['o.class_id'] = intval($param['class']);
            }
        }
        if (!empty($param['course']) && is_numeric($param['course'])) {
            //课程
            $where['cl.course_id'] = intval($param['course']);
        }

        if (!empty($param['way']) && is_numeric($param['way']) && $param['way'] != -1) {
            //缴费方式
            $where['o.payment'] = intval($param['way']);
        }

        if (isset($param['bstatus']) && is_numeric($param['bstatus']) && $param['bstatus'] != -1) {
            //发票状态
            $where['o.bill_status'] = intval($param['bstatus']);
        }

        if (isset($param['ostatus']) && is_numeric($param['ostatus']) && $param['ostatus'] != -1) {
            //支付状态
            $where['o.order_status'] = intval($param['ostatus']);
        }

        if (!empty($param['start_time']) && !empty($param['end_time'])) {
            //缴费时间
            $start = strtotime($param['start_time']);
            $end = strtotime('+23 hours 59 minutes 59 seconds', strtotime($param['end_time']));
            $where['o.pay_time'] = [['>= time', $start], ['<= time', $end]];
        } else {
            if (!empty($param['start_time'])) {
                $where['o.pay_time'] = ['>= time', strtotime($param['start_time'])];
            }
            if (!empty($param['end_time'])) {
                $end = strtotime('+23 hours 59 minutes 59 seconds', strtotime($param['end_time']));
                $where['o.pay_time'] = ['<= time', $end];
            }
        }

        //排序
        $sort = [
            'o.order_status' => 'asc',
            'o.id' => 'desc'
        ];

        //获取订单
        $order_mdl = new OrderModel();
        $data = $order_mdl->alias('o')
            ->field('o.*,t.name as student_name,sc.name as school_name,cr.course_name,us.realname as operator,u.realname,
            u.user_login as parent_name,u.mobile,u.address,b.payee,b.bill_type,b.tax_code,b.address,b.phone,b.bank,b.account,b.obtain_type')
            ->join('class cl','o.class_id=cl.id')
            ->join('school sc','cl.school_id=sc.id')
            ->join('course cr','cl.course_id=cr.id')
            ->join('student t','o.student_id=t.id')
            ->join('user u','o.parent_id=u.id')
            ->join('bill b','o.bill_id=b.id','left')
            ->join('user us','o.operator=us.id','left')
            ->where($where)
            ->order($sort)
            ->select();

        if (count($data) > 0) {
            $result = $data->toArray();
            // Create new PHPExcel object
            $objPHPExcel = new \PHPExcel();
            // Set properties
            $objPHPExcel->getProperties()->setCreator("ctos")
                ->setLastModifiedBy("ctos")
                ->setTitle("Office 2007 XLSX Test Document")
                ->setSubject("Office 2007 XLSX Test Document")
                ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                ->setKeywords("office 2007 openxml php")
                ->setCategory("Test result file");

            //设置列宽
            $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(10);
            $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10);
            $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(10);
            $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(10);
            $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(10);
            $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(10);

            //设置行高度
            $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(22);
            $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);

            //设置字体
            $objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);
            $objPHPExcel->getActiveSheet()->getStyle('A1:N1')->getFont()->setSize(14)->setBold(true);
            $objPHPExcel->getActiveSheet()->getStyle('A2:N2')->getFont()->setBold(true);
            $objPHPExcel->getActiveSheet()->getStyle('A2:N2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $objPHPExcel->getActiveSheet()->getStyle('A2:N2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//            $objPHPExcel->getActiveSheet()->getStyle('A2:N2')->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);

            //设置水平居中
            $objPHPExcel->getActiveSheet()->getStyle('A1:N1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //合并
            $objPHPExcel->getActiveSheet()->mergeCells('A1:N1');

            // set table header content
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', '财务收入表')
                ->setCellValue('A2', '编号')
                ->setCellValue('B2', '学生')
                ->setCellValue('C2', '家长')
                ->setCellValue('D2', '手机号')
                ->setCellValue('E2', '学校')
                ->setCellValue('F2', '班级')
                ->setCellValue('G2', '课程')
                ->setCellValue('H2', '优惠金额(元)')
                ->setCellValue('I2', '实付金额(元)')
                ->setCellValue('J2', '支付状态')
                ->setCellValue('K2', '缴费方式')
                ->setCellValue('L2', '缴费时间')
                ->setCellValue('M2', '发票')
                ->setCellValue('N2', '经办人');

            // Miscellaneous glyphs, UTF-8
            $total = count($result);
            for ($i = 0; $i < $total; $i++) {
                switch ($result[$i]['payment']) {
                    case 0:
                        $payment = '微信';
                        break;
                    case 1:
                        $payment = '支付宝';
                        break;
                    case 2:
                        $payment = '现金';
                        break;
                    case 3:
                        $payment = '银行卡';
                        break;
                    case 4:
                        $payment = '代金券';
                        break;
                    case 5:
                        $payment = '其他';
                        break;
                    default:
                        $payment = '';
                        break;
                }

                switch ($result[$i]['order_status']) {
                    case 0:
                        $order_status = '待支付';
                        break;
                    case 1:
                        $order_status = '已支付';
                        break;
                    case 2:
                        $order_status = '已完成';
                        break;
                    case 3:
                        $order_status = '已取消';
                        break;
                    case 4:
                        $order_status = '已退课';
                        break;
                    default:
                        $order_status = '';
                        break;
                }

                if ($result[$i]['bill_status'] == 2) {
                    $bill_status = '已开';
                } elseif ($result[$i]['bill_status'] == 1) {
                    $bill_status = '未开';
                } else {
                    $bill_status = '不需要';
                }

                if ($result[$i]['order_status'] == 0 || $result[$i]['order_status'] == 3) {
                    $pay_time = '';
                } else {
                    $pay_time = date('Y-m-d H:i', $result[$i]['pay_time']);
                }

                $objPHPExcel->getActiveSheet(0)->setCellValue('A' . ($i + 3), $result[$i]['order_id']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('B' . ($i + 3), $result[$i]['student_name']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('C' . ($i + 3), $result[$i]['realname']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('D' . ($i + 3), $result[$i]['mobile']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('E' . ($i + 3), $result[$i]['school_name']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('F' . ($i + 3), $result[$i]['class_name']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('G' . ($i + 3), $result[$i]['course_name']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('H' . ($i + 3), $result[$i]['discount_amout']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('I' . ($i + 3), $result[$i]['pay_amount']);
                $objPHPExcel->getActiveSheet(0)->setCellValue('J' . ($i + 3), $order_status);
                $objPHPExcel->getActiveSheet(0)->setCellValue('K' . ($i + 3), $payment);
                $objPHPExcel->getActiveSheet(0)->setCellValue('L' . ($i + 3), $pay_time);
                $objPHPExcel->getActiveSheet(0)->setCellValue('M' . ($i + 3), $bill_status);
                $objPHPExcel->getActiveSheet(0)->setCellValue('N' . ($i + 3), $result[$i]['operator']);
                $objPHPExcel->getActiveSheet()->getStyle('A' . ($i + 3) . ':N' . ($i + 3))->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $objPHPExcel->getActiveSheet()->getStyle('A' . ($i + 3) . ':N' . ($i + 3))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $objPHPExcel->getActiveSheet()->getRowDimension($i + 3)->setRowHeight(16);

            }
            // Rename sheet
            $objPHPExcel->getActiveSheet()->setTitle('财务收入');

            // Set active sheet index to the first sheet
            $objPHPExcel->setActiveSheetIndex(0);

            ob_end_clean();//清除缓冲区,避免乱码

            // Redirect output to a client’s web browser (Excel5)
            header('Content-Type: application/vnd.ms-excel');
            $filename = '财务收入信息' . '(' . date('Ymd-His') . ').xls';
            header('Content-Disposition: attachment;filename="' . $filename . '"');
            header('Cache-Control: max-age=0');

            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');

            $this->success('导出成功', 'financial/index');

        } else {
            $this->error('没有符合条件的订单信息，导出失败', 'financial/index');
        }
    }


    /**
     * 退费管理
     * @return mixed
     */
    public function refund()
    {
        $param = $this->request->param();
        $where['sr.delete_time'] = ['eq', 0];
        $classes = [];
        $class_mdl = new ClassModel();
        $filter = $this->request->param();

        $homework_starttime = empty($filter['homework_starttime']) ? 0 : strtotime($filter['homework_starttime']);
        $homework_endtime = empty($filter['homework_endtime']) ? 0 : strtotime($filter['homework_endtime']);
        if (!empty($homework_starttime) && !empty($homework_endtime)) {
            $where['sr.create_time'] = [['>= time', $homework_starttime], ['<= time', $homework_endtime]];
        } else {
            if (!empty($homework_starttime)) {
                $where['sr.create_time'] = ['>= time', $homework_starttime];
            }
            if (!empty($homework_endtime)) {
                $where['sr.create_time'] = ['<= time', $homework_endtime];
            }
        }
        if (!empty($filter['way']) && is_numeric($filter['way'])) {
            //付费方式 支付宝 微信 银行卡
            $where['sr.way'] = ['eq', trim($filter['way'])];
        }
        if (!empty($filter['status']) && is_numeric($filter['status'])) {
            //处理 未处理
            $where['sr.status'] = ['eq', trim($filter['status'])];
        }

        if (!empty($filter['school_id']) && is_numeric($filter['school_id'])) {
            //学校
            $where['c.school_id'] = intval($filter['school_id']);

            //获取该学校的班级
            $class_where = [
                'shop_id' => ['eq', $this->admin_shop_id],
                'school_id' => ['eq', $filter['school_id']],
            ];
            $class = $class_mdl->getClassByField($class_where);
            if (count($class) > 0) {
                $classes = $class;
            }

            if (!empty($filter['class_id']) && is_numeric($filter['class_id'])) {
                //班级
                $where['sr.class_id'] = intval($filter['class_id']);
            }
        }

        if (!empty($filter['course_id']) && is_numeric($filter['course_id'])) {
            //课程
            $where['c.course_id'] = ['eq', trim($filter['course_id'])];
        }

        //获取退课信息列表
        $field = 'sr.*,o.bill_status,cc.course_name ccname,c.name cname,s.name sname,t.name tname,u.realname as napplicant,us.realname as noperator';
        $data = Db::name('order_refund')->alias('sr')
            ->field($field)
            ->join('order o', 'sr.order_id=o.id')
            ->join('class c', 'c.id=sr.class_id')
            ->join('school s', 's.id=c.school_id')
            ->join('course cc', 'cc.id=c.course_id')
            ->join('student t', 't.id=sr.student_id')
            ->join('user u','sr.applicant=u.id','left')
            ->join('user us','sr.operator=us.id','left')
            ->where($where)
            ->order('sr.id', 'DESC')
            ->paginate(10, false, ['query' => $filter]);

        //获取学校
        $school_mdl = new SchoolModel();
        $schools = $school_mdl->getAllSchool($this->admin_shop_id);
        //获取课程
        $course_mdl = new CourseModel();
        $courses = $course_mdl->getAllCourse($this->admin_shop_id);

        $this->assign('data', $data);
        $this->assign('param', $param);
        $this->assign('schools', $schools);
        $this->assign('classes', $classes);
        $this->assign('courses', $courses);

        return $this->fetch();
    }

    /**
     *处理退费
     */
    public function refundHandle()
    {
        $id = $this->request->param('id');
        if (!isset($id) || empty($id) || !is_numeric($id)) {
            $this->error('参数有误');
        }
        //获取退课信息
        $refund_info = Db::name('order_refund')->find($id);
        if (count($refund_info) <= 0) {
            $this->error('没有该退课信息');
        }

        $class_id = $refund_info['class_id'];
        $student_id = $refund_info['student_id'];

        Db::startTrans();
        try {
            //标记为已退费
            $refund_data = [
                'status' => 2,
                'operator' => cmf_get_current_admin_id(),
            ];
            Db::name('order_refund')->where(['id' => $id])->update($refund_data);
            Db::name('class_student')->where(['class_id' => $class_id, 'student_id' => $student_id])->update(['is_refuse' => 2]);

            //修改订单状态为已退课
            Db::name('order')->where('id', $refund_info['order_id'])->update(['order_status' => 4]);
            //获取家长
            $condition = [
                'id' => ['eq', $refund_info['order_id']],
                'student_id' => ['eq', $student_id],
                'class_id' => ['eq', $class_id],
            ];
            $user_id = Db::name('order')->where($condition)->value('parent_id');
            //退费到账户余额
            Db::name('user')->where('id', $user_id)->setInc('balance', $refund_info['refuse_price']);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('处理失败');
        }

        //记录日志
        $table = 'order_refund,order,class_student,user';
        $pk = $id;
        $student_name = db::name("student")->where('id', $student_id)->value('name');
        $class_name = db::name("class")->where('id', $class_id)->value('name');
        $content = lang('CONFIRM_REFUND', ['sname' => $student_name, 'cname' => $class_name, 'price' => $refund_info['refuse_price']]);
        do_log($content, $pk, $table, time());

        $this->success('处理成功');
    }

    /**
     *取消退费
     */
    public function refundCancel()
    {
        $id = $this->request->param('id');
        if (!isset($id) || empty($id) || !is_numeric($id)) {
            $this->error('参数有误');
        }
        //获取退课信息
        $refund_info = Db::name('order_refund')->find($id);
        if (count($refund_info) <= 0) {
            $this->error('没有该退课信息');
        }

        $class_id = $refund_info['class_id'];
        $student_id = $refund_info['student_id'];

        Db::startTrans();
        try {
            //标记为未退费
            Db::name('order_refund')->where(['id' => $id])->update(['delete_time' => time(), 'status' => 0]);

            if (isset($_SESSION['student_status']) && is_numeric($_SESSION['student_status'])) {
                $student_status = $_SESSION['student_status'];
            } else {
                $student_status = 0;
            }
            //从班级中取消删除学生，并标记为未退费
            $condition = [
                'student_id' => $student_id,
                'class_id' => $class_id,
                'shop_id' => $this->admin_shop_id,
            ];
            Db::name('class_student')->where($condition)->update(['delete_time' => 0, 'student_status' => $student_status, 'is_refuse' => 0]);

            //查看座位
            $seat_where = [
                'student_id' => $student_id,
                'classes_id' => $class_id,
                'shop_id' => $this->admin_shop_id,
            ];
            //取消删除座位
            Db::name('class_seat')->where($seat_where)->update(['delete_time' => 0]);
            //班级报名人数加一
            Db::name('class')->where(['id' => $class_id])->setInc('current_num');

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('处理失败');
        }

        //记录日志
        $table = 'order_refund,class_student,class_seat,class';
        $pk = $id;
        $student_name = db::name("student")->where('id', $student_id)->value('name');
        $class_name = db::name("class")->where('id', $class_id)->value('name');
        $content = lang('CANCEL_REFUND', ['sname' => $student_name, 'cname' => $class_name]);
        do_log($content, $pk, $table, time());

        $this->success('处理成功');
    }

    /*
     * 手动修改支付
     */
    public function pay()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $payment = $post['payment'];
            $id = $post['id'];
            if (empty($id) || !is_numeric($id) || !is_numeric($payment)) {
                $this->error('参数错误');
            }
            //订单状态
            $order_status = 1;

            //备注
            if (isset($post['remark'])) {
                $remark = trim($post['remark']);
            } else {
                $remark = '';
            }

            $update_data = [
                'operator' => cmf_get_current_admin_id(),//经办人
                'order_status' => $order_status,
                'remark' => $remark,
                'payment' => $payment,
                'pay_time' => time()
            ];
            $order_mdl = new OrderModel();
            $res = $order_mdl->where(['id' => $id])->update($update_data);
            if ($res) {
                $this->success('处理成功');
            } else {
                $this->error('处理失败');
            }

        }
    }

    /**
     *手动设置订单价格
     */
    public function setOrderPrice()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            //成功标记
            $result = 1;
            //设置的优惠价格
            $discount = trim($post['discount']);
            //订单编号
            $order_id = trim($post['id']);
            if (empty($order_id) || !is_numeric($order_id) || !is_numeric($discount)) {
                $this->error('参数错误');
            }
            //获取订单
            $order = Db::name('order')->find($order_id);
            if(count($order) <= 0){
                $this->error('该订单不存在');
            }
            //订单总金额
            $amount = $order['amount'];
            //优惠金额
            $discount_amount = $order['discount_amout'];
            //实际支付金额
            $pay_amount = $amount - $discount_amount - $discount;
            $pay_amount = number_format($pay_amount,2);
            if($pay_amount < 0){
                $this->error('优惠金额不能大于实际支付金额');
            }

            Db::startTrans();
            try{
                $order_data = [
                    'pay_discount' => $discount,
                    'pay_amount' => $pay_amount,
                    'update_time' => time(),
                ];
                Db::name('order')->where(['id'=>$order_id])->update($order_data);
                Db::commit();

            }catch (Exception $e){
                Db::rollback();
                $result = 0;
            }

            if($result == 1){
                //记录日志
                $log_data = [
                    'orderId' => $order['order_id'],
                    'discount' => $discount,
                    'realpay' => $pay_amount,
                ];
                $content = lang('ORDER_SET', $log_data);
                do_log($content, $order_id, 'order', time());

                $this->success('设置成功');
            }else{
                $this->error('保存失败');
            }

        }else{
            $this->error('请求错误');
        }
    }

    /**
     * 取消订单
     */
    public function cancel()
    {
        $id = $this->request->param('id');
        //获取订单
        $order_mdl = new OrderModel();
        $order = $order_mdl->find($id);
        if (count($order) <= 0) {
            $this->error('该订单不存在');
        }

        //订单已过期，修改订单状态,同时释放座位，优惠返回等相关操作
        $update_data = [
            'id' => $id,
            'order_status' => 3,//已取消
            'update_time' => time(),
        ];
        //修改订单
        $result_order = $order_mdl->editOrder($update_data);
        if (!$result_order) {
            $this->error('取消订单失败');
        }

        //释放座位
        $class_mdl = new ClassModel();
        $result_seat = $class_mdl->releaseSeat($order['class_id'], $order['student_id'], $this->admin_shop_id);
        if (!$result_seat) {
            $this->error('释放座位失败');
        }

        //释放优惠
        $award_where = [
            'student_id' => $order['student_id'],
            'order_id' => $order['id'],
        ];
        $seat = Db::name('award_order')->where($award_where)->find();
        if (count($seat) > 0) {
            Db::name('award_order')->where($award_where)->delete();
        }

        //记录日志
        $content = lang('ORDER_CANCEL', ['orderId' => $order['order_id']]);
        do_log($content, $id, 'order', time());

        $this->success('取消订单成功');
    }

}